<template>
  <div class="app-container">
    <div class="filter-container">
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate" >
            添加
        </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="编号"  align="center" >
        <template slot-scope="{row}">
          <span>  {{ row.id }}</span>
        </template>
      </el-table-column>
     
      <el-table-column label="标题" align="center"> 
        <template slot-scope="{row}">
          <span class="link-type" >{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片"  align="center">
        <template slot-scope="{row}">
           <el-image
                style="width: 260px; height: 120px"
                :src="row.img"
                fit="contain"
            ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="链接" min-width="110px" align="center">
        <template slot-scope="{row}">
          <span >{{ row.url }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80px" align="center">
        <template slot-scope="{row}">
            <el-tag class="ml-2" type="success" v-if="row.status == 1">显示</el-tag>
            <el-tag class="ml-2" type="info" v-else>隐藏</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="100px" align="center">
        <template slot-scope="{row}">
          <span >{{ row.solt }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
                 <el-button type="primary" size="mini" @click="handleUpdate(row)">
                  编辑
                </el-button>
          <el-popconfirm
              confirm-button-text="是"
              cancel-button-text="取消"
              icon-color="red"
              title="你是否确定删除此数据?"
                @onConfirm="handleDelete(row,$index)"
            >
              <template #reference>
                <el-button size="mini" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
      
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" >
       
         <el-form-item label="banner图片" prop="img">
          <el-upload
            class="avatar-uploader"
            :action="domain"
            :data="QiniuData"
            :show-file-list="false"
            :on-remove="handleRemove"
            :on-success="uploadSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="temp.img" :src="temp.img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <span>750px*300px</span>
         </el-form-item>
        <el-form-item label="标题" prop="title" >
          <el-input v-model="temp.title"/>
        </el-form-item>
         <el-form-item label="链接" prop="url" >
                    <el-input
                v-model="temp.url"
                placeholder="banner链接"
              />
        </el-form-item>
         <el-form-item label="排序" prop="solt">
          <el-input v-model="temp.solt" maxlength="6"/>
        </el-form-item>
         <el-form-item label="状态" prop="status">
            <el-radio v-model="temp.status" label="1" size="large">显示</el-radio>
            <el-radio v-model="temp.status" label="2" size="large">隐藏</el-radio>
        </el-form-item>
       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { GQL } from '@/api/article'
import { getToken } from '@/api/qiniu'

export default {
  name: 'ComplexTable',

  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
        temp:{
            title:'',
            img:'',
            solt:'',
            url:'',
            status:'',
            createtime:''
        },
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }]
      },
      showReviewer: false,
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
            update: '编辑banner',
            create: '新增banner'
        },
        QiniuData: {
        key: "yssl", //图片名字处理
        token: "" ,//七牛云token
        data:{}
      },
      domain: "http://upload-z2.qiniup.com", // 七牛云的上传地址（华东区）
        qiniuaddr: "http://r92t5xgkc.hn-bkt.clouddn.com", // 七牛云的
    }
  },
  created() {
     this.getList()
     
     this.Qiniutoken()
  },
  methods: {
        Qiniutoken(){
        getToken().then(response => {
          // console.log('77777777777',response)
           this.QiniuData.token= response.data
        //   resolve(true)
        })
    },
    handleRemove(file, fileList) {
    this.uploadPicUrl = "";
    },
    handleExceed(files, fileList) {
        this.$message.warning(
            `当前限制选择一个文件，如需更换，请删除上一个文件在重新选择！`
        );
    },
    beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
    },
    beforeAvatarUpload(file) {   //图片上传之前的方法
        const isJPG = file.type === 'image/jpg';
        const isJPEG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        
        // const isOgg = file.type === "video/ogg";
      
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG && !isJPEG && !isPNG ) {
          this.$message.error("上传文件只能是 jpeg,jpg,png 格式!");
          return false;
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
          return false;
        }
        // file.name = 
        var time = new Date().getTime();
        const filename = time + file.name;
        this.QiniuData.data = file;
        this.QiniuData.key = filename;
    },

    uploadSuccess(response, file, fileList) {  //图片上传成功的方法

    // this.imageUrl = `${this.qiniuaddr}/${response.key}`;
      this.temp.img = `${this.qiniuaddr}/${response.key}`;
      // console.log('1111111----------',this.temp);
    },
    getList() {
      this.listLoading = true
     
        const query = {
               "operationName": "allSlSystemBanners",
                "query": "query allSlSystemBanners { allSlSystemBanners { nodes { createtime id img solt status title url } } }",
                "variables":""
        }
       GQL(query).then(response => {
        this.list = response.data.allSlSystemBanners.nodes
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
      
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
         title:'',
            img:'',
            solt:'',
            url:'',
            status:'',
      }
    },
     handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
       handleUpdate(row) {
    //   this.resetTemp()
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData(){
        const query = {
          "operationName": "createSlSystemBanner",
          "query": "mutation createSlSystemBanner($input: CreateSlSystemBannerInput!) { createSlSystemBanner(input: $input) { slSystemBanner { id solt } } }",
          "variables": {"input": {"slSystemBanner": this.temp}}
        }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          GQL(query).then((res) => {
            if(res.errors){
                this.$notify({
                  title: '添加失败',
                  message: '新增banner失败',
                  type: 'error',
                  duration: 2000
                })
            }else{
                this.temp.id = res.data.createSlSystemBanner.slSystemBanner.id
               this.list.unshift(this.temp)
                this.dialogFormVisible = false
                this.$notify({
                  title: '添加成功',
                  message: '新增banner成功',
                  type: 'success',
                  duration: 2000
                })
                
            }
          })
        }
      })
    },
     updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          let query = {
            "operationName": "updateSlSystemBannerById",
            "query": "mutation updateSlSystemBannerById($input: UpdateSlSystemBannerByIdInput!) { updateSlSystemBannerById(input: $input) { slSystemBanner { id img } } }",
            "variables": {input: {id: tempData.id, slSystemBannerPatch:tempData}}
          }
          GQL(query).then((res) => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
               if(res.errors){
                  this.$notify({
                    title: '修改banenr失败',
                    message: '修改banner失败',
                    type: 'error',
                    duration: 2000
                  })
              }else{
                  this.list.splice(index, 1, this.temp)
                  this.dialogFormVisible = false
                  this.$notify({
                    title: '修改banner成功',
                    message: '修改banner项目成功',
                    type: 'success',
                    duration: 2000
                  })
                  
              }
       
          })
        }
      })
    },
    handleDelete(row, index) {
       
          let query = {
            "operationName": "deleteSlSystemBannerById",
            "query": "mutation deleteSlSystemBannerById($input:DeleteSlSystemBannerByIdInput!) { deleteSlSystemBannerById(input:$input) { deletedSlSystemBannerId } }",
            "variables": {input: {id: row.id}}
          }
          GQL(query).then((res) => {
               if(res.errors){
                  this.$notify({
                    title: '删除失败',
                    message: '删除项目失败',
                    type: 'error',
                    duration: 2000
                  })
              }else{
                  this.$notify({
                    title: '删除成功',
                    message: '删除项目成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.list.splice(index, 1)
              }
      
          })
        
    }
  }
}
</script>
<style scoped>
.demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 350px;
    height: 180px;
    display: block;
  }
</style>
